<script lang="ts">
    import Icon from "../Common/Icons/Icon.svelte";
    import { useClassList } from "../utils/useClassList";
    import { useStyle } from "../utils/useStyle";
    import { isColor } from "../utils/utils";
    import type { DropdownItemProps } from "./Dropdown";
    import { useDropdownContext } from "./Dropdown.svelte";

    const props: DropdownItemProps = $props();
    const ctx: any = useDropdownContext();
    const { theme, disabled, divided, selected, arrow, name, data, icon, children, ...others } = props;

    const themeName = isColor(props.theme) ? "" : props.theme;
    const classList = $derived(
        useClassList(props, "cm-dropdown-item", {
            "cm-dropdown-item-disabled": props.disabled,
            "cm-dropdown-item-divided": props.divided,
            "cm-dropdown-item-selected": props.selected,
            "cm-dropdown-item-with-arrow": props.arrow,
            [`cm-dropdown-item-${themeName}`]: themeName,
        })
    );

    const onClick = (e: any) => {
        if (props.disabled) {
            return;
        }
        e.preventDefault();
        e.stopPropagation();
        ctx?.onSelect(props.name, props.data);
    };

    const styles = $derived(
        useStyle(props, {
            "--cui-dropdown-text-color": isColor(props.theme) ? props.theme : "",
        })
    );
</script>

<li class={classList} {...others} style={styles} onclick={onClick}>
    {#if props.icon}
        <span class="cm-dropdown-item-icon">{@render props.icon()}</span>
    {/if}
    {@render props.children?.()}
    {#if props.arrow}
        <Icon icon="chevronRight" class="cm-dropdown-item-arrow"></Icon>
    {/if}
</li>
